package dao

import (
	"fmt"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
)

const (
	POSITION_GROUP    string = "group"
	POSITION_AREA     string = "area"
	POSITION_FARM     string = "farm"
	POSITION_SELF     string = "self"
	POSITION_SERVICE  string = "service"
	POSITION_ENGINEER string = "engineer"
)

// method GET/PUT/POST/DELETE
func AddOpLog(userid string, url string, method string, content string) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	db.Model("t_op_log").Data(g.Map{
		"userid":  userid,
		"url":     url,
		"method":  method,
		"content": content,
	}).Insert()
}

func NeedSaveLog(url string, method string) (save bool) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	one, _ := db.GetOne(fmt.Sprintf("SELECT * FROM t_api_map WHERE api='%s' AND instr(method,'%s');", url, method))
	if one != nil {
		item := one.Map()
		enable_log := gconv.Int(item["enable_log"])
		if enable_log > 0 {
			save = true
		} else {
			save = false
		}
	} else {
		save = false
	}
	return save
}

func GetUserIdByOpenID(openid string) (userid string, err error) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	model := db.Model("t_user")
	m, e := model.Where("wx_openid=?", openid).One()
	if e != nil {
		err = e
	} else {
		if m != nil {
			userid = gconv.String(m.Map()["userid"])
		}
	}
	return userid, err
}

func GetUserGroupCode(userid string) (group_code string) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	model := db.Model("t_user")
	r, _ := model.Where(fmt.Sprintf("userid='%s'", userid)).One()
	if r != nil {
		m := r.Map()
		group_code = gconv.String(m["group_code"])
	}
	return group_code
}

func GetUserAreaIds(userid string) (area_ids string) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	model := db.Model("v_user")
	r, _ := model.Where(fmt.Sprintf("userid='%s'", userid)).One()
	if r != nil {
		m := r.Map()
		area_ids = gconv.String(m["area_ids"])
	}
	return area_ids
}

func GetUserFarmIds(userid string) (farmid_ids string) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	model := db.Model("v_user")
	r, err := model.Where(fmt.Sprintf("userid='%s'", userid)).One()
	if err != nil {
		g.Log().Line(true).Error(err)
	} else {
		if r != nil {
			m := r.Map()
			farmid_ids = gconv.String(m["farmid_ids"])
		}
	}

	return farmid_ids
}

func GetUserPositionType(userid string) (position_type string) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	model := db.Model("t_user")
	r, _ := model.Where(fmt.Sprintf("userid='%s'", userid)).One()
	if r != nil {
		m := r.Map()
		position_type = gconv.String(m["position_type"])
	}
	return position_type
}

func GetPermitUserList(userid string, where ...string) (userList gdb.List) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	model := db.Model("v_user")
	if IsAdmin(userid) {
		//全部用户
	} else {
		position_type := GetUserPositionType(userid)
		if position_type == POSITION_GROUP {
			//集团管理员具有整个集团的用户
			group_code := GetUserGroupCode(userid)
			model.Where(fmt.Sprintf(" group_code='%s' AND is_admin=0 ", group_code))
		} else if position_type == POSITION_AREA {
			//团长具有团区内养殖场所有用户
			area_ids := GetUserAreaIds(userid)
			model.Where(fmt.Sprintf(" (FIND_IN_SET(area_ids,'%s') or FIND_IN_SET('%s',area_ids)) AND is_admin=0 AND position_type in ('area','farm','self')  ", area_ids, area_ids))
		} else if position_type == POSITION_FARM {
			//场长具有养殖场所有用户
			farmid_ids := GetUserFarmIds(userid)
			model.Where(fmt.Sprintf(" (FIND_IN_SET(farmid_ids,'%s') or FIND_IN_SET('%s',farmid_ids)) AND is_admin=0 AND position_type in ('farm','self') ", farmid_ids, farmid_ids))
		} else {
			//只能看到自己
			model.Where(fmt.Sprintf(" userid='%s' ", userid))
		}
	}

	if len(where) == 0 {
	} else {
		model = model.Where(" 1=1 " + where[0])
	}
	res, err := model.All()
	if err != nil {
		g.Log().Line().Error(err)
		return nil
	}
	return res.List()
}

func GetPermitUserids(userid string, where ...string) (userids string) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	model := db.Model("v_user")
	if IsAdmin(userid) {
		//全部用户
	} else {
		position_type := GetUserPositionType(userid)
		if position_type == POSITION_GROUP {
			//集团管理员具有整个集团的用户
			group_code := GetUserGroupCode(userid)
			model.Where(fmt.Sprintf(" group_code='%s' AND is_admin=0 ", group_code))
		} else if position_type == POSITION_AREA {
			//团长具有团区内养殖场所有用户
			area_ids := GetUserAreaIds(userid)
			model.Where(fmt.Sprintf(" (FIND_IN_SET(area_ids,'%s') or FIND_IN_SET('%s',area_ids)) AND is_admin=0 AND position_type in ('area','farm','self')  ", area_ids, area_ids))
		} else if position_type == POSITION_FARM {
			//场长具有养殖场所有用户
			farmid_ids := GetUserFarmIds(userid)
			model.Where(fmt.Sprintf(" (FIND_IN_SET(farmid_ids,'%s') or FIND_IN_SET('%s',farmid_ids)) AND is_admin=0 AND position_type in ('farm','self') ", farmid_ids, farmid_ids))
		} else {
			//只能看到自己
			model.Where(fmt.Sprintf(" userid='%s' ", userid))
		}
	}

	if len(where) == 0 {
	} else {
		model = model.Where(" 1=1 " + where[0])
	}
	res, err := model.Fields("userid").All()
	if err != nil {
		g.Log().Line().Error(err)
		return ""
	} else {
		idArr := res.Array("userid")
		userids = gstr.JoinAny(idArr, ",")
	}
	return userids
}

func GetPermisRols(userid string, where ...string) (roleList gdb.List) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	model := db.Model("t_role")
	if IsAdmin(userid) {
		//全部用户
	} else {
		position_type := GetUserPositionType(userid)
		if position_type == POSITION_GROUP {
			model.Where(" position_type in ('group','area','farm','self') ")
		} else if position_type == POSITION_AREA {
			model.Where(" position_type in ('area','farm','self') ")
		} else if position_type == POSITION_FARM {
			model.Where(" position_type in ('farm','self') ")
		} else if position_type == POSITION_SELF {
			model.Where(" position_type in ('self') ")
		} else {
			model.Where(" 1>2 ")
		}
	}

	if len(where) == 0 {
	} else {
		model = model.Where(where[0])
	}
	res, err := model.Order(" `sort_idx` asc").All()
	if err != nil {
		g.Log().Line().Error(err)
		return nil
	}
	return res.List()
}

func GetPermisGroup(userid string, where ...string) (groupList gdb.List) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	model := db.Model("t_group")
	if IsAdmin(userid) || IsService(userid) {
		//全部用户
	} else {
		model.Where(fmt.Sprintf(" group_code in (SELECT group_code FROM t_user WHERE userid='%s') ", userid))
	}

	if len(where) == 0 {
	} else {
		model = model.Where(where[0])
	}
	res, err := model.Order(" `sort_idx` asc").All()
	if err != nil {
		g.Log().Line().Error(err)
		return nil
	}
	return res.List()
}

func GetPermisArea(userid string, where ...string) (groupList gdb.List) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	model := db.Model("v_area")
	if IsAdmin(userid) || IsService(userid) {
		//全部用户
	} else {
		position_type := GetUserPositionType(userid)
		if position_type == POSITION_GROUP {
			//看到下级所有区域
			group_code := GetUserGroupCode(userid)
			model.Where(fmt.Sprintf(" group_code='%s' ", group_code))
		} else {
			//看到有权限的区域
			model.Where(fmt.Sprintf(" id in (SELECT area_id FROM t_user_area WHERE userid='%s') ", userid))
		}
	}

	if len(where) == 0 {
	} else {
		model = model.Where(where[0])
	}
	res, err := model.Order(" `sort_idx` asc").All()
	if err != nil {
		g.Log().Line().Error(err)
		return nil
	}
	return res.List()
}

func GetPermisFarm(userid string, where ...string) (farmList gdb.List) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	model := db.Model("v_farm")
	if IsAdmin(userid) || IsService(userid) {
		//全部用户
	} else {
		position_type := GetUserPositionType(userid)
		if position_type == POSITION_GROUP {
			//集团
			group_code := GetUserGroupCode(userid)
			model.Where(fmt.Sprintf(" area_id in (SELECT id FROM t_area WHERE group_code='%s') ", group_code))
		} else if position_type == POSITION_AREA {
			//组团
			area_ids := GetUserAreaIds(userid)
			model.Where(fmt.Sprintf(" (FIND_IN_SET(area_id,'%s') or FIND_IN_SET('%s',area_id)) ", area_ids, area_ids))
		} else if position_type == POSITION_FARM {
			//场
			farmid_ids := GetUserFarmIds(userid)
			model.Where(fmt.Sprintf(" (FIND_IN_SET(id,'%s') or FIND_IN_SET('%s',id)) ", farmid_ids, farmid_ids))
		} else {
			//其他
			farmid_ids := GetUserFarmIds(userid)
			model.Where(fmt.Sprintf(" (FIND_IN_SET(id,'%s') or FIND_IN_SET('%s',id)) ", farmid_ids, farmid_ids))
		}
	}

	if len(where) == 0 {
	} else {
		model = model.Where(where[0])
	}
	res, err := model.Order("  `sort` desc").All()
	if err != nil {
		g.Log().Line().Error(err)
		return nil
	}
	return res.List()
}

func GetPermisHouse(userid string, where ...string) (farmList gdb.List) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	model := db.Model("v_house")
	if IsAdmin(userid) || IsService(userid) {
		//全部用户
	} else {
		position_type := GetUserPositionType(userid)
		if position_type == POSITION_GROUP {
			//集团
			group_code := GetUserGroupCode(userid)
			model.Where(fmt.Sprintf(" area_id in (SELECT id FROM t_area WHERE group_code='%s') ", group_code))
		} else if position_type == POSITION_AREA {
			//组团
			area_ids := GetUserAreaIds(userid)
			model.Where(fmt.Sprintf(" (FIND_IN_SET(area_id,'%s') or FIND_IN_SET('%s',area_id)) ", area_ids, area_ids))
		} else if position_type == POSITION_FARM {
			//场
			farmid_ids := GetUserFarmIds(userid)
			model.Where(fmt.Sprintf(" (FIND_IN_SET(farmid,'%s') or FIND_IN_SET('%s',farmid)) ", farmid_ids, farmid_ids))
		} else {
			//其他
			farmid_ids := GetUserFarmIds(userid)
			model.Where(fmt.Sprintf(" (FIND_IN_SET(farmid,'%s') or FIND_IN_SET('%s',farmid)) ", farmid_ids, farmid_ids))
		}
	}

	if len(where) == 0 {
	} else {
		model = model.Where(where[0])
	}
	res, err := model.Order(" `sort` desc,id asc,housename asc").All()
	if err != nil {
		g.Log().Line().Error(err)
		return nil
	}
	return res.List()
}

func GetPermisDevice(userid string, where ...string) (farmList gdb.List) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	model := db.Model("v_device")
	if IsAdmin(userid) || IsService(userid) {
		//全部用户
	} else {
		position_type := GetUserPositionType(userid)
		if position_type == POSITION_GROUP {
			//集团
			group_code := GetUserGroupCode(userid)
			model.Where(fmt.Sprintf(" group_code='%s' ", group_code))
		} else if position_type == POSITION_AREA {
			//组团
			area_ids := GetUserAreaIds(userid)
			model.Where(fmt.Sprintf(" (FIND_IN_SET(area_id,'%s') or FIND_IN_SET('%s',area_id)) ", area_ids, area_ids))
		} else if position_type == POSITION_FARM {
			//场
			farmid_ids := GetUserFarmIds(userid)
			model.Where(fmt.Sprintf(" (FIND_IN_SET(farmid,'%s') or FIND_IN_SET('%s',farmid)) ", farmid_ids, farmid_ids))
		} else {
			//其他
			farmid_ids := GetUserFarmIds(userid)
			model.Where(fmt.Sprintf(" (FIND_IN_SET(farmid,'%s') or FIND_IN_SET('%s',farmid)) ", farmid_ids, farmid_ids))
		}
	}

	if len(where) == 0 {
	} else {
		model = model.Where(where[0])
	}
	res, err := model.Order(" `houseid` asc").All()
	if err != nil {
		g.Log().Line().Error(err)
		return nil
	}
	return res.List()
}

func SetPermisAddWhere(userid string) (addWhere string) {
	if IsAdmin(userid) || IsService(userid) {
		//全部用户
	} else {
		position_type := GetUserPositionType(userid)
		if position_type == POSITION_GROUP {
			//集团
			group_code := GetUserGroupCode(userid)
			addWhere = fmt.Sprintf(" and group_code='%s' ", group_code)
		} else if position_type == POSITION_AREA {
			//组团
			area_ids := GetUserAreaIds(userid)
			addWhere = fmt.Sprintf(" and (FIND_IN_SET(area_id,'%s') or FIND_IN_SET('%s',area_id)) ", area_ids, area_ids)
		} else if position_type == POSITION_FARM {
			//场
			farmid_ids := GetUserFarmIds(userid)
			addWhere = fmt.Sprintf(" and (FIND_IN_SET(farmid,'%s') or FIND_IN_SET('%s',farmid)) ", farmid_ids, farmid_ids)
		} else {
			//其他
			farmid_ids := GetUserFarmIds(userid)
			addWhere = fmt.Sprintf(" and (FIND_IN_SET(farmid,'%s') or FIND_IN_SET('%s',farmid)) ", farmid_ids, farmid_ids)
		}
	}
	return addWhere
}

// IsAdmin 是否管理员
func IsAdmin(userid interface{}) bool {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	user, err := db.Model("t_user").Where("userid=?", userid).One()
	if err != nil {
		g.Log().Line().Error(err)
		return false
	}
	if user.Map()["admin"] == 1 {
		return true
	}
	return false
}

// IsService 是否售后
func IsService(userid interface{}) bool {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	user, err := db.Model("t_user_roles").Where("userid=? and role_id='service'", userid).One()
	if err != nil {
		g.Log().Line().Error(err)
		return false
	}
	if user != nil {
		return true
	}
	return false
}

// isGroupAdmin 是否集团管理员
func isGroupAdmin(userid interface{}) bool {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	user, err := db.Model("t_user_roles").Where(fmt.Sprintf("userid='%s' and role_id='group_admin'", userid)).One()
	if err != nil {
		g.Log().Line().Error(err)
		return false
	}
	if user != nil {
		return true
	}
	return false
}

// isAreaAdmin 是否团管理员
func isAreaAdmin(userid interface{}) bool {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	user, err := db.Model("t_user_roles").Where("userid=? and role_id='area_admin'", userid).One()
	if err != nil {
		g.Log().Line().Error(err)
		return false
	}
	if user != nil {
		return true
	}
	return false
}

// isFarmAdmin 是否场区管理员
func isFarmAdmin(userid interface{}) bool {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	user, err := db.Model("t_user_roles").Where("userid=? and role_id='farm_admin'", userid).One()
	if err != nil {
		g.Log().Line().Error(err)
		return false
	}
	if user != nil {
		return true
	}
	return false
}

func CheckApiPermission(api string, method string, userid string) (res bool) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if !IsAdmin(userid) {
		r, err := db.Model("t_user").Where(fmt.Sprintf(" userid='%s' and status>0", userid)).All()
		if err != nil {
			g.Log().Line().Error(err)
			return false
		} else {
			users := r.List()
			if len(users) > 0 {
				count, err := db.Model("v_permission").Where("userid=? and api=? and method like '%"+method+"%'", userid, api).Count()
				if err != nil {
					g.Log().Line().Error(err)
					return false
				}
				if count <= 0 {
					return false
				} else {
					return true
				}
			} else {
				return false
			}
		}

	} else {
		return true
	}
	return
}

// 获取当前用户有权限的设备
func GetUserDevice(userid string) (res gdb.List, err error) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	var r gdb.Result
	if IsAdmin(userid) || IsService(userid) {
		r, err = db.Model("v_device").All()
	} else {
		r, err = db.GetAll(fmt.Sprintf("SELECT * FROM v_user_device WHERE userid='%s';", userid))
	}
	if err == nil {
		res = r.List()
	}
	return res, err
}

func GetSnByAddrTn(addr string, tn int) (sn string) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	node, err := db.Model("t_hzfgw_node_para").Where("addr=? and tn=?", addr, tn).Fields("sn").One()
	if err != nil {
		g.Log().Line(true).Error(err)
	} else {
		if node != nil {
			item := node.Map()
			sn = gconv.String(item["sn"])
		}
	}
	return sn
}
